<template>
  <aside class="Sidebar">
    <h2></h2>
    <div class="nav-top">
      <div title="纵胜MES(WEB版)" class="com-logo-box">
        <img src="../assets/logo.png" alt="Logo" class="admin-logo" />
        <span class="admin-title">纵胜新材</span>
      </div>
      <div class="admin-info">
        <!-- <span class="admin-name">管理员</span>
        <span class="admin-role">超级管理员</span> -->
      </div>
    </div>
    <!-- 左边栏begin -->
    <div class="sidebar-content">
      <el-menu
        :default-active="activeIndex"
        class="el-menu-vertical-demo"
        :collapse="isCollapsed"
        background-color="#ffffff"
        text-color="#000000"
        active-text-color="#93e362"
        @select="handleMenuSelect"
        :unique-opened="true">
        <template v-for="item in menuTree" :key="item.menu_id">
          <el-sub-menu
            v-if="hasValidChildren(item)"
            :index="String(item.menu_id)">
            <template #title>
              <el-icon v-if="item.icon"><component :is="getIconComponent(item.icon)" /></el-icon>
              <span>{{ item.menu_name }}</span>
            </template>
            <template v-for="child in item.children" :key="child.menu_id">
              <el-sub-menu
                v-if="hasValidChildren(child)"
                :index="String(child.menu_id)">
                <template #title>
                  <el-icon v-if="child.icon"><component :is="getIconComponent(child.icon)" /></el-icon>
                  <span>{{ child.menu_name }}</span>
                </template>
                <el-menu-item
                  v-for="grandChild in child.children"
                  :key="grandChild.menu_id"
                  :index="String(grandChild.menu_id)"
                  @click="handleMenuItemClick(grandChild)">
                  <el-icon v-if="grandChild.icon"><component :is="getIconComponent(grandChild.icon)" /></el-icon>
                  <span>{{ grandChild.menu_name }}</span>
                </el-menu-item>
              </el-sub-menu>
              <el-menu-item
                v-else
                :index="String(child.menu_id)"
                @click="handleMenuItemClick(child)">
                <el-icon v-if="child.icon"><component :is="getIconComponent(child.icon)" /></el-icon>
                <span>{{ child.menu_name }}</span>
              </el-menu-item>
            </template>
          </el-sub-menu>
          <el-menu-item
            v-else
            :index="String(item.menu_id)"
            @click="handleMenuItemClick(item)">
            <el-icon v-if="item.icon"><component :is="getIconComponent(item.icon)" /></el-icon>
            <span>{{ item.menu_name }}</span>
          </el-menu-item>
        </template>
      </el-menu>
    </div>
    <!-- 左边栏end -->
  </aside>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useSysMenuStore } from '@/stores/sys/SysMenuStore'
import { getIconComponent } from '@/utils/iconUtils'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const menuStore = useSysMenuStore()
const isCollapsed = ref(false)
const activeIndex = ref('')

// 检查是否有有效的子菜单
const hasValidChildren = (item) => {
  return item.children &&
         Array.isArray(item.children) &&
         item.children.length > 0 &&
         item.children.some(child => child && child.menu_name)
}

// 使用菜单树结构而不是平面列表
const menuTree = computed(() => {
  return menuStore.menuTree || []
})

// 更新当前激活的菜单索引
function updateActiveIndex(currentPath) {
  if (!currentPath) return

  const menus = menuTree.value

  function findActiveIndex(items) {
    for (const item of items) {
      if (item.menu_path === currentPath) {
        return String(item.menu_id)
      }

      if (hasValidChildren(item)) {
        const childResult = findActiveIndex(item.children)
        if (childResult) {
          return childResult
        }
      }
    }
    return null
  }

  const index = findActiveIndex(menus)
  if (index) {
    activeIndex.value = index
  }
}

// 在组件挂载时加载菜单数据
onMounted(async () => {
  try {
    await menuStore.fetchMenuList()
  } catch (error) {
    console.error('Failed to load menu data:', error)
  }
})

// 监听路由变化，更新激活的菜单项
watch(
  () => route.path,
  (newPath) => {
    updateActiveIndex(newPath)
  },
  { immediate: true }
)

// 处理菜单项点击
const handleMenuItemClick = (item) => {
  if (item.menu_path) {
    router.push(item.menu_path)
  } else {
    console.warn(`菜单项 ${item.menu_name} 没有配置路径`)
  }
}

// 处理菜单选择事件（兼容Element Plus事件）
const handleMenuSelect = (index) => {
  try {
    // 查找被选中的菜单项
    const menuItem = findMenuItemByIndex(index)

    if (menuItem && menuItem.menu_path) {
      router.push(menuItem.menu_path)
    } else if (menuItem) {
      console.warn(`菜单项 ${menuItem.menu_name} 没有配置路径`)
    } else {
      console.error(`未找到index为${index}的菜单项`)
    }
  } catch (error) {
    console.error('处理菜单选择事件时出错:', error)
  }
}

// 根据索引查找菜单项
function findMenuItemByIndex(targetIndex) {
  const menus = menuTree.value

  function search(items) {
    for (const item of items) {
      if (String(item.menu_id) === targetIndex) {
        return item
      }

      if (hasValidChildren(item)) {
        const found = search(item.children)
        if (found) return found
      }
    }
    return null
  }

  return search(menus)
}
</script>

<style scoped>
/* 样式部分保持不变 */
.active-link {
  font-weight: bold;
  color: #ffdd57 !important;
}
</style>
<style scoped>
.el-aside {
  height: 100vh;
  overflow-y: auto;
  width: 250px;
  background-color: #42b983;
  font-weight: bold;
  color: #ffdd57 !important;
  position: fixed;
  left: 0;
  top: 0;
}
</style>

<style scoped>
.sidebar-content {
  position: fixed;
  left: 0;
  width: 250px;
  height: 100vh;
  background-color: #42b983;
  overflow-y: auto;
}

.el-menu {
  height: auto;
  min-height: 100%;
  background-color: #42b983;
  font-weight: bold;
  width: 250px;
  :deep(.el-sub-menu.is-opened) {
    background-color: #d3d5d5;
  }

  :deep(.el-menu-item) {
    background-color: #e2e7e5;
  }

  :deep(.el-menu-item.is-active) {
    background-color: #ffdd57 !important;
    color: #000000 !important;
  }
}
</style>

<style scoped>
.Sidebar {
  width: 250px;
  background-color: #42b983;
  padding: 20px;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  height: 100vh;
  left: 0;
  top: 0;
}
.com-logo-box {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.admin-logo {
  width: 50px;
  height: auto;
  max-width: 100%;
  border-radius: 10px;
}
.admin-title {
  font-size: 24px;
  color: #ffffff;
  margin-left: 10px;
  line-height: 1;
  vertical-align: middle;
}
</style>